package schedule

import (
	"context"
	task2 "github.com/beherochuling/beesoft_api/app/model/task"
	"github.com/beherochuling/beesoft_api/app/service/task/task"
	"github.com/gogf/gf/v2/os/gctx"
	"os"
	"strconv"

	"github.com/gogf/gf/v2/frame/g"

	"github.com/beherochuling/beesoft_api/app/helper/helper"
)

func Work() {
	ctx := gctx.New()

	hostName, _ := os.Hostname()
	helper.Info("hostname", hostName)

	nodeType := "other"
	helper.Info("nodetype", nodeType)

	serviceTypes := task2.NodeConfig[nodeType]

	for _, serviceType := range serviceTypes {
		go workForService(ctx, serviceType)
	}
}
func workForService(ctx context.Context, serviceType string) {
	config := g.Cfg().MustGet(ctx, "queue").MapStrStr()
	helper.Info("consume"+serviceType, config)

	for {
		if Can(serviceType) {
			event := task.Task.Pop(ctx, serviceType)
			if event != nil {
				helper.Info("consume "+serviceType, event.UUID)
				go task.Task.Run(ctx, event)
				helper.Sleep(config["timeInterval"])
				continue
			}

			helper.Info("consume "+serviceType, "queue empty")
			timeIntervalEmpty, err := strconv.Atoi(config["timeIntervalEmpty"])
			if err != nil {
				panic(err)
			}
			helper.Sleep(timeIntervalEmpty)
			continue
		}

		helper.Info("consume "+serviceType, "not promit")
		helper.Sleep(config["timeIntervalCannot"])
	}
}
func Can(serviceType string) bool {
	return true
}
